package com.gitlab.bootren.data.core.jpa.impl;

import com.gitlab.bootren.data.core.query.ICondition;

import javax.persistence.Query;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

 

public class ParamUtils {

	public static void setParamToQuery(Query query,ICondition condition){
		for(String  key : condition.getParams().keySet()){
			Object value = condition.getParams().get(key);
			if(value!=null){
				if(value.getClass().isArray()){
					
					List params = new ArrayList();
					for(int i=0;i<Array.getLength(value);i++){
						params.add(Array.get(value, i));
					}
					query.setParameter(key, params);
				}else{
                                    /*
                                       if(value instanceof Date){
                                           query.setParameter(key,(Date)value,TemporalType.DATE);
                                       }else{
                                           query.setParameter(key, value);
                                       }
					*/
                                    query.setParameter(key, value);
				}
			
				
			}
		}
	}
	
	
	public static String appendCondition(String ql,String condition){
		if(ql.toLowerCase().indexOf(" where ")!=-1){
			ql+= " and " +condition ;
		}else{
			ql+= " where " +condition ;
		}
		return ql ;
	}
	
/**
	public static String getAname (String ql){
		String result = null;
		Pattern pattern = Pattern.compile("select[\\s]+([^\\s]+)[\\s]+from.+",Pattern.CASE_INSENSITIVE );
		Matcher matcher = pattern.matcher(ql);
		if(matcher.matches()){
			result = matcher.group(1);
		}
		if(result!=null&&result.indexOf("(")>0){
			Pattern  p1 =  Pattern.compile(".*\\(([^\\*\\.]*)(\\.[^\\)]+)?\\).*",Pattern.CASE_INSENSITIVE );
			Matcher m1 = p1.matcher(result);
			if(m1.matches()){
				result = m1.group(1);
			}
		}
		
		if(result==null){
			Pattern  p1 =  Pattern.compile("^\\s*from\\s+[^\\s]+\\s+(as[\\s]+)?([^\\s]+).*",Pattern.CASE_INSENSITIVE );
			Matcher m1 = p1.matcher(ql);
			if(m1.matches()){
				result = m1.group(2);
			}
		}
		return result;
	}
	
**/	
	
	
}
